package main

import (
	"DistributeCalculator/task"
	"context"
	"errors"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"net"
)

type primary struct {
	taskQueen   taskQueen
	workerCount int
}

//client invoke
func (this *primary) PushTask(ctx context.Context, req *task.ClientRequest) (*task.NULL, error) {
	this.taskQueen.TaskWaitingPush(req)
	fmt.Printf("已经接收到%v的任务，请等待任务的分配\n", req.ClientID)
	return &task.NULL{}, nil
}
func (this *primary) PullResult(ctx context.Context, taskID *task.TaskID) (*task.ResponseForClient, error) {
	result, _ := this.taskQueen.selectResult(taskID)

	//这一段的目的就是为了寻找有没有一个重复3次以上的结果，有就返回，否则返回请等待
	resultC := make(map[string]int, 0)
	for _, r := range result {
		rtmp := r.GetTask().GetResult()
		for k, v := range resultC {
			if rtmp == k {
				if v >= 3 {
					fmt.Printf("任务%v的处理结果即将返回\n", taskID.GetTaskID())
					return &task.ResponseForClient{Task: r.GetTask()}, nil
				}
			}
		}
		resultC[rtmp]++
	}

	return &task.ResponseForClient{}, errors.New("please wait...")
}

//worker invoke
func (this *primary) PullTask(context.Context, *task.NULL) (*task.ClientRequest, error) {
	if this.taskQueen.TaskWaitingQueenSize() > 0 {
		fmt.Printf("任务已经分配，请等待计算结果\n")
		this.workerCount++
		if this.workerCount <= 3 {
			return this.taskQueen.GetLastWaitingTask(), nil
		} else {
			return this.taskQueen.TaskWaitingPop(), nil
		}

	}
	return &task.ClientRequest{}, errors.New("tasks are finished all, please wait... ")
}
func (this *primary) PushResult(ctx context.Context, res *task.WorkerResponse) (*task.NULL, error) {
	this.taskQueen.TaskResultPush(res)
	//fmt.Printf("加入结果队列之后的长度%v", len(this.taskQueen.taskResultQueen))
	fmt.Printf("任务%v已经计算完成，已经加入结果队列\n", res.Task.TaskID.GetTaskID())
	return &task.NULL{}, nil
}

func server() {
	rpcServer := grpc.NewServer()
	listen, err := net.Listen("tcp", ":8081")
	if err != nil {
		log.Fatalf("端口无法使用, Error %v", err)
		return
	}
	task.RegisterTaskServiceServer(rpcServer, new(primary))
	rpcServer.Serve(listen)
}
